package cn.com.nes.site.service.workOrder.impl;


import cn.com.nes.common.util.MapUtils;
import cn.com.nes.site.entity.bo.workorder.WorkOrderBO;
import cn.com.nes.site.entity.em.crm.customer.CustomerLevelEnum;
import cn.com.nes.site.entity.em.crm.customer.CustomerNatureEnum;
import cn.com.nes.site.service.crm.customer.CrmCustomerService;
import cn.com.nes.site.service.crm.customer.CustomerHouseRelationshipService;
import cn.com.nes.site.service.crm.customer.CustomerHouseService;
import cn.com.nes.site.service.crm.customer.CustomerStaffService;
import cn.com.nes.site.service.crm.customer.bo.CustomerBO;
import cn.com.nes.site.service.crm.customer.bo.CustomerStaffBO;
import cn.com.nes.site.service.crm.customer.dto.CustomerDTO;
import cn.com.nes.site.service.crm.customer.dto.CustomerStaffDTO;
import cn.com.nes.site.service.system.region.XzqhService;
import cn.com.nes.site.service.workOrder.WorkOrderRecordService;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;
import java.util.UUID;

@Data
public abstract class WorkOrderBuilder {
    private static final BigDecimal DEFAULT_HEATING_LOAD = new BigDecimal(45); // 默认热负荷为 45W
    @Resource
    private CrmCustomerService crmCustomerService;
    @Resource
    private XzqhService xzqhService;
    @Resource
    private CustomerHouseService customerHouseService;

    @Resource
    private WorkOrderRecordService workOrderRecordService;

    @Resource
    private CustomerHouseRelationshipService customerHouseRelationshipService;

    @Resource
    private CustomerStaffService customerStaffService;

    /**
     * 返回不同类型
     */
    public abstract String getType();

    /**
     * 保存工单的方法
     */
    @Transactional(rollbackFor = Exception.class)
    public String saveWorkOrder(WorkOrderBO workOrderBO) throws Exception {
        if (StringUtils.isEmpty(workOrderBO.getXzqhdm())) {
            workOrderBO.setXzqhdm(workOrderBO.getUserInfo().getAreacode());
        }
        setCoordinate(workOrderBO);
        customerSave(workOrderBO);
        saveEquipmentInfo(workOrderBO);
        validDefaultField(workOrderBO);
        String workOrderId = createWorkOrder(workOrderBO);
        saveWorkOrderRecord(workOrderBO, workOrderId);
        sendAliSms(workOrderBO);
        if(StringUtils.isNotEmpty(workOrderId)){
            return "保存成功";
        }else{
            return "保存失败";
        }
    }

    /**
     * 校验用户,并生成用户
     */
    private void customerSave(WorkOrderBO workOrderBO) throws Exception {
        if (StringUtils.isEmpty(workOrderBO.getClienteleId())) {
            CustomerBO customer = new CustomerBO();
            customer.setUuid(UUID.randomUUID().toString());
            customer.setCustomerName(workOrderBO.getCustomerName());
            customer.setPhone(workOrderBO.getPhone());
            customer.setXzqhdm(workOrderBO.getXzqhdm());
            customer.setCustomerLevel(CustomerLevelEnum._level_2);
            customer.setCustomerNature(CustomerNatureEnum._personal);
            customer.setLongitude(workOrderBO.getLongitude());
            customer.setLatitude(workOrderBO.getLatitude());
            customer.setXzqhdm(workOrderBO.getXzqhdm());
            customer.setOperateUserId(workOrderBO.getOperateUserId());
            customer.setOperateDate(workOrderBO.getOperateDate());
            customer.setOperateUserCompanyId(workOrderBO.getOperateUserCompanyId());
            customer.setOperateUserName(workOrderBO.getOperateUserName());
            customer.setUserInfo(workOrderBO.getUserInfo());
            customer.setAddCustomer(true);
            //保存用户
            CustomerDTO customerDTO = crmCustomerService.customerSave(customer);
            workOrderBO.setClienteleId(customerDTO.getUuid());
            workOrderBO.setHouseId(customerDTO.getHouseId());
            workOrderBO.setHouseUUid(customerDTO.getHouseUUid());
        }
        CustomerStaffDTO customerStaffDTO = customerStaffService.getMainCustomerStaff(workOrderBO.getClienteleId());
        if (ObjectUtil.isNotEmpty(customerStaffDTO)) {
            customerStaffService.saveCustomerStaff(buildCustomerStaffBo(customerStaffDTO, workOrderBO));
        }
    }

    /**
     * 保存设备信息
     */
    protected abstract void saveEquipmentInfo(WorkOrderBO workOrderBO) throws Exception;


    /**
     * 设置坐标
     */
    private void setCoordinate(WorkOrderBO workOrderBO) {
        if (ObjectUtil.isEmpty(workOrderBO.getLatitude())) {
            Map<String, BigDecimal> coordinate = xzqhService.getCoordinate(workOrderBO.getXzqhdm());
            if (ObjectUtil.isEmpty(coordinate)) {
                JSONObject geo = MapUtils.getGeoByAddress(workOrderBO.getAddress(), workOrderBO.getXzqhdm());
                if (ObjectUtil.isNotNull(geo)) {
                    workOrderBO.setLatitude(BigDecimal.valueOf(geo.getDouble("lat")));
                    workOrderBO.setLongitude(BigDecimal.valueOf(geo.getDouble("lng")));
                }
            } else {
                workOrderBO.setLatitude(coordinate.get("latitude"));
                workOrderBO.setLongitude(coordinate.get("longitude"));
            }
        }
    }

    /**
     * 创建工单差异化参数校验
     */
    protected abstract void validDefaultField(WorkOrderBO workOrderBO) throws Exception;

    /**
     * 创建工单
     */
    protected abstract String createWorkOrder(WorkOrderBO workOrderBO) throws Exception;


    /**
     * 保存日志
     */
    protected abstract void saveWorkOrderRecord(WorkOrderBO workOrderBO, String workOrderId) throws Exception;


    protected abstract void sendAliSms(WorkOrderBO workOrderBO);
    @NotNull
    private CustomerStaffBO buildCustomerStaffBo(CustomerStaffDTO bo, WorkOrderBO workOrderBO) {
        CustomerStaffBO customerStaffBO = new CustomerStaffBO();
        customerStaffBO.setId(Long.parseLong(bo.getId()));
        customerStaffBO.setCustomerUuid(bo.getCustomerId());
        customerStaffBO.setPhone(workOrderBO.getPhone());
        customerStaffBO.setName(workOrderBO.getCustomerName());
        customerStaffBO.setOperateUserId(workOrderBO.getOperateUserId());
        customerStaffBO.setOperateDate(workOrderBO.getOperateDate());
        customerStaffBO.setIsMain(1);
        //是否联系人已经有户主了，如果有户主了，就不能是户主了
        if(ObjectUtil.isNotNull(customerStaffService.getHouseholdCustomerStaff(bo.getCustomerId()))){
            customerStaffBO.setIsHousehold(0);
        }else{
            customerStaffBO.setIsHousehold(1);
        }
        return customerStaffBO;
    }
}
